class HD {
	static PENDING = 'PENDING'
	static FUFILLED = 'FUFILLED'
	static REJECT = 'REJECT'

	constructor (executor) {
		this.status = HD.PENDING
		this.callbacks = [] // 保存回调函数的数组
		this.value = null
		setTimeout(() => {
			try {
				executor(this.resolve.bind(this), this.reject.bind(this))
			} catch (error) {
				// 当executor内部发生异常，也要执行reject
				this.reject (error)
			}
		})
	}

	/* 成功回调函数 */
	resolve (value) {
		if (this.status === HD.PENDING) {
			this.value = value
			this.status = HD.FUFILLED
			// 成功之后调用成功方法
			setTimeout(() => {
				this.callbacks.forEach(callback => {
					callback.onResolved(value)
				})
			})
		}
	}

	/* 失败回调函数 */
	reject (reason) {
		if (this.status === HD.PENDING) {
			this.value = reason
			this.status = HD.REJECT
			// 失败之后调用失败方法
			setTimeout(() => {
				this.callbacks.forEach(callback => {
					callback.onRejected(reason)
				})
			})
		}
	}

	then (onResolved = () => {}, onRejected = () => {}) {
		console.log(this)
		return new HD((resolve, reject) => {
			// 初始化时，保存传入的两个回调函数
			if (this.status === HD.PENDING) {
				this.callbacks.push({
					onResolved: value => {
						try {
							onResolved(value)
						} catch (error) {
							onRejected(error)
						}
					},
					onRejected: reason => {
						try {
							onRejected(reason)
						} catch (error) {
							console.error(error)
							onRejected(error)
						}
					}
				})
			}
			if (this.status === HD.FUFILLED) {
				setTimeout(() => {
					try {
						const result = onResolved(this.value)
						resolve(result)
					} catch (error) {
						onRejected(error)
					}
				})
			}

			if (this.status === HD.REJECT) {
				setTimeout(() => {
					try {
						const result = onRejected(this.value)
						resolve(result)
					} catch (error) {
						onRejected(error)
					}
				})
			}
		})
	}
}